package com.ruoyi.web.controller.organization;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.organization.domain.BizPeople;
import com.ruoyi.organization.domain.vo.*;
import com.ruoyi.organization.service.IBizPeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 村民Controller
 *
 * @author ruoyi
 * @date 2024-05-10
 */
@RestController
@RequestMapping("/organization/people")
public class BizPeopleController extends BaseController {

    @Autowired
    private IBizPeopleService bizPeopleService;

    /**
     * 查询村民列表
     */
    @PreAuthorize("@ss.hasPermi('organization:people:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizPeople bizPeople) {
        startPage();
        List<BizPeople> list = bizPeopleService.selectBizPeopleList(bizPeople);
        TableDataInfo dataTable = getDataTable(list);
        dataTable = bizPeopleService.doPeopleGird(dataTable);
        return dataTable;
    }

    /**
     * 查看家庭成员
     */
    @PreAuthorize("@ss.hasPermi('organization:people:list')")
    @GetMapping("/familyPeople")
    public TableDataInfo familyPeople(FamilyPeople familyPeople) {
        List<BizPeople> list = bizPeopleService.familyPeople(familyPeople);
        return getDataTable(list);
    }

    /**
     * 导出村民列表
     */
    @PreAuthorize("@ss.hasPermi('organization:people:export')")
    @Log(title = "村民", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizPeople bizPeople) {
        // List<BizPeople> list = bizPeopleService.selectBizPeopleList(bizPeople);
        // ExcelUtil<BizPeople> util = new ExcelUtil<BizPeople>(BizPeople.class);
        // util.exportExcel(response, list, "村民数据");
    }

    /**
     * 获取村民详细信息
     */
    @PreAuthorize("@ss.hasPermi('organization:people:query')")
    @GetMapping(value = "/{peopleId}")
    public AjaxResult getInfo(@PathVariable("peopleId") Long peopleId) {
        return success(bizPeopleService.selectBizPeopleByPeopleId(peopleId));
    }

    /**
     * 新增村民
     */
    @PreAuthorize("@ss.hasPermi('organization:people:add')")
    @Log(title = "村民", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizPeople bizPeople) {
        bizPeople.setCreateBy(getUsername());
        return toAjax(bizPeopleService.insertBizPeople(bizPeople));
    }

    /**
     * 修改村民
     */
    @PreAuthorize("@ss.hasPermi('organization:people:edit')")
    @Log(title = "村民", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizPeople bizPeople) {
        bizPeople.setUpdateBy(getUsername());
        return toAjax(bizPeopleService.updateBizPeople(bizPeople));
    }

    @PreAuthorize("@ss.hasPermi('organization:people:edit')")
    @Log(title = "设置当前用户是否为户主", businessType = BusinessType.UPDATE)
    @PutMapping("/setHeadCard")
    public AjaxResult setHeadCard(@RequestBody BizPeople bizPeople) {
        bizPeople.setUpdateBy(getUsername());
        return toAjax(bizPeopleService.setHeadCard(bizPeople));
    }

    @PreAuthorize("@ss.hasPermi('organization:people:edit')")
    @Log(title = "审核居民", businessType = BusinessType.UPDATE)
    @PutMapping("/auditPeople")
    public AjaxResult auditPeople(@RequestBody BizPeople bizPeople) {
        bizPeople.setUpdateBy(getUsername());
        return toAjax(bizPeopleService.auditPeople(bizPeople));
    }

    /**
     * 删除村民
     */
    @PreAuthorize("@ss.hasPermi('organization:people:remove')")
    @Log(title = "村民", businessType = BusinessType.DELETE)
    @DeleteMapping("/{peopleIds}")
    public AjaxResult remove(@PathVariable Long[] peopleIds) {
        return toAjax(bizPeopleService.deleteBizPeopleByPeopleIds(peopleIds));
    }

    /**
     * 导入用户数据
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BizPeopleVo> util = new ExcelUtil<BizPeopleVo>(BizPeopleVo.class);
        List<BizPeopleVo> userList = util.importExcel(file.getInputStream());
        if (StrUtil.isBlank(userList.get(0).getCommunity())) {
            ExcelUtil<BizPeople2Vo> util2 = new ExcelUtil<BizPeople2Vo>(BizPeople2Vo.class);
            List<BizPeople2Vo> userList2 = util2.importExcel(file.getInputStream());
            userList = new ArrayList<>();
            for (BizPeople2Vo bizPeople2Vo : userList2) {
                BizPeopleVo bizPeopleVo = new BizPeopleVo();
                BeanUtils.copyProperties(bizPeople2Vo, bizPeopleVo);
                userList.add(bizPeopleVo);
            }
        }
        LoginUser loginUser = getLoginUser();
        String operName = loginUser.getUsername();
        String message = bizPeopleService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @Log(title = "导入网格员", businessType = BusinessType.IMPORT)
    @PostMapping("/importGridData")
    public AjaxResult importGridData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BizBridVo> util = new ExcelUtil<BizBridVo>(BizBridVo.class);
        List<BizBridVo> userList = util.importExcel(file.getInputStream());
        if (StrUtil.isBlank(userList.get(0).getCommunity())) {
            ExcelUtil<BizBridVo2> util2 = new ExcelUtil<BizBridVo2>(BizBridVo2.class);
            List<BizBridVo2> userList2 = util2.importExcel(file.getInputStream());
            userList = new ArrayList<>();
            for (BizBridVo2 bizBridVo2 : userList2) {
                BizBridVo BizBridVo = new BizBridVo();
                BeanUtils.copyProperties(bizBridVo2, BizBridVo);
                userList.add(BizBridVo);
            }
        }
        LoginUser loginUser = getLoginUser();
        String operName = loginUser.getUsername();
        String message = bizPeopleService.importGridData(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 下载导入模板
     *
     * @return
     */
    @PostMapping("/importTemplate/{type}")
    public void importTemplate(@PathVariable Integer type, HttpServletResponse response) {
        //居民模板
        switch (type) {
            case 1:
                ExcelUtil<BizPeopleVo> util_1 = new ExcelUtil<>(BizPeopleVo.class);
                util_1.importTemplateExcel(response, "表格模板");
                break;
            case 2:
                ExcelUtil<BizPeople2Vo> util_2 = new ExcelUtil<>(BizPeople2Vo.class);
                util_2.importTemplateExcel(response, "表格模板");
                break;
            case 3:
                ExcelUtil<BizBridVo> util_3 = new ExcelUtil<>(BizBridVo.class);
                util_3.importTemplateExcel(response, "表格模板");
                break;
            case 4:
                ExcelUtil<BizBridVo2> util_4 = new ExcelUtil<>(BizBridVo2.class);
                util_4.importTemplateExcel(response, "表格模板");
                break;
            default:
                throw new ServiceException("类型错误");
        }
    }

    /**
     * 下载村民身份牌
     *
     * @return
     */
    @PostMapping("/generatePeopleCard")
    public void generatePeopleCard(HttpServletResponse response, @Validated BizFamilyScoreLogVo people) {
        bizPeopleService.generatePeopleCard(response, people.getPeopleId());
    }

    /**
     * 查询基础报表
     */
    @GetMapping("/systemBoardView")
    public AjaxResult systemBoardView() {
        return AjaxResult.success(bizPeopleService.systemBoardView());
    }

    /**
     * 查询期间内每日的积分流水报表
     */
    @GetMapping("/getScoreLogGroupByDay")
    public AjaxResult getScoreLogGroupByDay(FamilyScoreLogViewParamVo paramVo) {
        return AjaxResult.success(bizPeopleService.getScoreLogGroupByDay(paramVo.getStartDate(), paramVo.getEndDate()));
    }

    @PreAuthorize("@ss.hasPermi('organization:people:edit')")
    @Log(title = "设置网格员", businessType = BusinessType.UPDATE)
    @PutMapping("/setGird")
    public AjaxResult setGird(@RequestBody GirdVo girdVo) {
        return toAjax(bizPeopleService.setGird(girdVo));
    }

    @PreAuthorize("@ss.hasPermi('organization:people:edit')")
    @Log(title = "设置党员", businessType = BusinessType.UPDATE)
    @PutMapping("/changeIsParty")
    public AjaxResult changeIsParty(@RequestBody BizPeople bizPeople) {
        return toAjax(bizPeopleService.changeIsParty(bizPeople));
    }

    @PreAuthorize("@ss.hasPermi('organization:people:list')")
    @Log(title = "查找户主信息", businessType = BusinessType.UPDATE)
    @PostMapping("/queryHeadCard")
    public AjaxResult queryHeadCard(@RequestBody BizPeople bizPeople) {
        return success(bizPeopleService.selectBizPeopleList(bizPeople));
    }

    @PreAuthorize("@ss.hasPermi('organization:people:list')")
    @Log(title = "设置用户迁入", businessType = BusinessType.UPDATE)
    @PostMapping("/setIngoing")
    public AjaxResult queryHeadCard(@RequestBody Ingoing ingoing) {
        return toAjax(bizPeopleService.setIngoing(ingoing, getUsername()));
    }

    @PreAuthorize("@ss.hasPermi('organization:people:edit')")
    @Log(title = "重置解绑网格员微信", businessType = BusinessType.UPDATE)
    @PutMapping("/resetWx")
    public AjaxResult resetPeopleOpenId(@RequestBody BizPeople bizPeople) {

        return toAjax(bizPeopleService.resetWx(bizPeople,getUsername()));
    }
    @PreAuthorize("@ss.hasPermi('organization:people:edit')")
    @Log(title = "重置普通居民的微信号", businessType = BusinessType.UPDATE)
    @PutMapping("/resetCommonWx")
    public AjaxResult resetCommonWx(@RequestBody BizPeople bizPeople) {

        return toAjax(bizPeopleService.resetCommonWx(bizPeople,getUsername()));
    }
    @PreAuthorize("@ss.hasPermi('organization:people:edit')")
    @Log(title = "变更社区", businessType = BusinessType.UPDATE)
    @PutMapping("/doSetCommunity")
    public AjaxResult doSetCommunity(@RequestBody BizSetCommunity bizSetCommunity) {

        return toAjax(bizPeopleService.doSetCommunity(bizSetCommunity,getUsername()));
    }


}
